﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Notes_CommonDev.MiddleWare
{
    public class URLRewriteMiddleware
    {
        private readonly RequestDelegate _next;

        //Your constructor will have the dependencies needed for database access
        public URLRewriteMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            if (context.Request.Headers.TryGetValue("ApiVer", out StringValues ver) && ver == "2.0")
            {
                if (!context.Request.Path.StartsWithSegments("/op"))
                {
                    var path = context.Request.Path.ToUriComponent().ToLowerInvariant();
                    path = path.Replace("api", "op");
                    context.Request.Path = path.Replace("vipget", "Vip.Info.Get");
                    context.Request.Path = path.Replace("vipmodify", "Vip.Info.Modify");
                }
            }
            await _next.Invoke(context);
        }
    }
}
